<template>
  <div class="login">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <input v-model="username" placeholder="用户名" />
      <input v-model="password" type="password" placeholder="密码" />
      <button type="submit">登录</button>
    </form>
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const username = ref('')
const password = ref('')
const error = ref('')
const router = useRouter()

const handleLogin = async () => {
  try {
    const res = await axios.post('http://localhost:3000/login', {
      username: username.value,
      password: password.value,
    })

    if (res.data.success) {
      router.push({ name: 'MyPage', query: { id: res.data.id } })
    } else {
      error.value = res.data.message
    }
  } catch (e) {
    error.value = '请求失败，请检查服务器是否开启'
  }
}
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: 100px auto;
}
</style>
